package struts.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import struts.bean.vo.StrutsXmlVO;

public class ParseXmlByDom4j {

	/**
	 * @param args
	 * @throws DocumentException 
	 */
/*	public static void main(String[] args) throws DocumentException {
		Map <String,StrutsXmlVO> map=initXml("src/mvc/struts-config.xml");
		StrutsXmlVO s=map.get("depaction");
		System.out.println(" beanName:"+s.getBeanName()+"  beanClass:"+s.getBeanClass());
		Iterator it=map.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry entry=(Map.Entry)it.next();
			Object key=entry.getKey();
			StrutsXmlVO sb=(StrutsXmlVO)entry.getValue();
			//System.out.println("path:"+key+" beanName:"+sb.getBeanName()+"  beanClass:"+sb.getBeanClass());
		}

	}*/
	
	/**
	 * 初始化mvc框架,读取xml信息，并存入map中
	 */
	public static Map <String,StrutsXmlVO> initXml(String xmlpath){
		Map <String,StrutsXmlVO> xmlBeans =new HashMap();
		SAXReader read=new SAXReader();
		Document document=null;
		try {
			document = read.read(new File(xmlpath));
		} catch (DocumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Element root=document.getRootElement();
		Element beansEl=root.element("beans");
		List<Element> beansL=beansEl.elements("bean");
		for(Element e:beansL){
			StrutsXmlVO xb=new StrutsXmlVO();
			String beanName=e.attributeValue("name");
			String className=e.attributeValue("class");
			xb.setBeanName(beanName);
			xb.setBeanClass(className);
			Element actionE=root.element("action-mapping");
			List<Element> actions=actionE.elements("action");
			for(Element ea:actions){
				String ea_name=ea.attributeValue("name");
				if(ea_name.equals(beanName)){
					xb.setPath(ea.attributeValue("path"));
					xb.setActionClass(ea.attributeValue("type"));
					List<Element> forwarsE=ea.elements("forward");
					Map <String,String>forwardMap=new HashMap<String,String>();
					for(Element ef:forwarsE){
						String forwardName=ef.attributeValue("name");
						String forwardValue=ef.attributeValue("value");
						forwardMap.put(forwardName, forwardValue);
					}
					xb.setDispUrl(forwardMap);
					break;
				}
			}
			xmlBeans.put(xb.getPath(), xb);
		}
		return xmlBeans;
	}

}
